package com.top75;

import java.util.Stack;

/**
 * @Author: huangzhigao
 * @Date: 2023/5/16 20:36
 */
public class Code735 {
    public static int[] asteroidCollision(int[] asteroids) {
        Stack<Integer> stack = new Stack<>();
        for (int i = 0; i < asteroids.length; i++) {
            if (stack.isEmpty()) {
                stack.push(asteroids[i]);
            } else if (!stack.isEmpty() && asteroids[i] < 0) {
                while (!stack.isEmpty() && stack.peek() > 0 && stack.peek() < -asteroids[i]) {
                    stack.pop();
                }

                //情况1：当前为空， 加
                //情况2：当前的peek比较大 不操作
                //情况3，当前两个值相当 pop
                //情况4,当前peek也是负数 +
                if (!stack.isEmpty() && stack.peek() == -asteroids[i]) {
                    stack.pop();
                } else if (stack.isEmpty() || stack.peek() < 0) {
                    stack.push(asteroids[i]);
                }
            } else if (asteroids[i] > 0) {
                stack.push(asteroids[i]);
            }
        }

        int[] res = new int[stack.size()];
        int index = res.length;
        while (!stack.isEmpty()) {
            res[--index] = stack.pop();
        }
        return res;
    }

    public static void main(String[] args) {
        int[] nums = {5,10,-5};
        System.out.println(asteroidCollision(nums));
    }
}
